<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use InfyOm\Generator\Utils\ResponseUtil;
use Response;
use Route;
use DB;
use Illuminate\Support\Facades\Auth;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use App\Repositories\RoleRepository;
use App\Models\ParkInfo;
use App\Models\Role;

/**
 * @SWG\Swagger(
 *   basePath="/api/v1",
 *   @SWG\Info(
 *     title="Laravel Generator APIs",
 *     version="1.0.0",
 *   )
 * )
 * This class should be parent class for other API controllers
 * Class AppBaseControllerF
 */
class AppBaseController extends Controller
{

    /**
     * 成功返回数据
     *
     * @param $result
     * @param $message
     * @return mixed
     */
    public function sendResponse($result, $message, $code=200, $headers=[], $options=JSON_UNESCAPED_UNICODE)
    {
        return Response::json(
                    ResponseUtil::makeResponse($message, $result),
                    $code,
                    $headers,
                    $options
                );
    }

    /**
     * 页面或者数据不存在
     *
     * @param $error
     * @param int $code
     * @return mixed
     */
    public function sendError($error, $code = 400, $headers=[], $options=JSON_UNESCAPED_UNICODE)
    {
        return Response::json(
                    ResponseUtil::makeError($error), 
                    $code,
                    $headers,
                    $options
                );
    }

    /**
     * 未授权
     *
     * @param $error
     * @param int $code
     * @return mixed
     */
    public function sendApiError($error, $code = 403, $headers=[], $options=JSON_UNESCAPED_UNICODE)
    {
        return Response::json(
                    ResponseUtil::makeError($error), 
                    $code,
                    $headers,
                    $options
                );
    }

    /**
     * 授权监控日志
     * @param $logdata
     */
    public function log($logdata){
        $log = new Logger('air_port');
        $log->pushHandler(new StreamHandler(storage_path('logs/car_auth-'.date("Y-m-d").'.log'),Logger::INFO) );
        $log->addInfo($logdata);
    }

    /**
     * 递归获取类别下所有子类别ID
     * @return:
     */
    public function getBelongIds($ids=[], $id='')
    {
        $result = DB::table("menu")->whereIn('pid', $ids);
        if ($id) $result->orWhere('id', $id);
        $result = $result->get();
        if ($result)
        {
            $allIds = array_column(obj2arr($result), 'id');
            $temp = array_diff($allIds, $ids);
            if (count($temp)>0){
                return array_merge($allIds, $this->getBelongIds($temp));
            }else{
                return $allIds;
            }
        }else{
            return [];
        }
    }

    /*
    *  导出车辆追踪
    */
    function export($data,$title,$file_name){
        if(empty($data)){
            return  $this->sendError('没有数据导出');
        }
        $res['file_name'] = $file_name;
        if(file_exists(storage_path("app/public/".$file_name))){
            return  $this->sendResponse($res, '查询成功');
        }
        //其中$array为数据(已经有相应的格式)，$temp_img（已经确定了以列名为key，所有的图片地址值为value的形式）
        $out = fopen(storage_path("app/public/".$file_name), 'w');
        fwrite($out, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
        fputcsv($out, $title);
        foreach ($data as $item) {
            fputcsv($out, $item);
        }
        fclose($out);
        return  $this->sendResponse($res, '查询成功');
    }

    /**
     *
     * @return key park_code
     * @return value parking_name
     */
    function getUserParks(){
        $user = Auth::user();
        if(!isset($user->roles)){
            return [];
        }
        $roles = $user->roles;
        $role_ids_arr = array_column(obj2arr($roles),'id','name');
        if(array_key_exists('admin', $role_ids_arr)){
            $park_res = ParkInfo::active()->pluck("parking_name","park_code");
        } else {
            $park_ids = Role::WhereIn("id", $role_ids_arr)
                ->leftJoin("role_has_park","role_has_park.role_id",'=',"roles.id")
                ->pluck("park_id");

            $park_res = ParkInfo::whereIn("park_code",$park_ids)->pluck("parking_name","park_code");
        }
        return $park_res;
    }

    /**
     * 获取park_code数组
     *
     * @param $parks
     * @return array
     */
    public function getParkCodes($parks)
    {
        if(!$parks){
            return [];
        }
        $parkCode = array_keys($parks->toArray());

        foreach ($parkCode as $k=>$item){
            $parkCode[$k]=(string) $item;
        };
        return $parkCode;
    }

    /*
    *  发送短信
    * @exp   $content = $route_res->r_username.",".$route_res->r_user_phone.",".date("Y-m-d H:i:s",$route_res->r_order_start_time).",".$data['start_place']."--".$data['end_place'].",". $route_res->r_car_back_place;
    * @param $tpl string m_driver_rec,m_driver_confirm
    */
//    function sendMsg($phone, $arr, $tpl){
//        if(empty($phone)) return;
//        $cont = implode(',', $arr);
//        try{
//            //手机短信
//            $service = app('mobilemsg');
//            $resp = $service->send($phone,$cont,$tpl);
//        }catch (\Exception $ex){
//            return response()->json([
//                's' => 0,
//                'm' => $ex->getMessage()
//            ]);
//        }
//    }

}
